package com.arcbbs.service.impl;

import com.arcbbs.config.WebConfig;
import com.arcbbs.constant.BaseConstant;
import com.arcbbs.entity.SessionWebUserDto;
import com.arcbbs.entity.UserInfo;
import com.arcbbs.entity.UserIntegralRecord;
import com.arcbbs.entity.UserMessage;
import com.arcbbs.enums.FileUploadTypeEnum;
import com.arcbbs.enums.UserIntegralOperTypeEnum;
import com.arcbbs.exception.BaseException;
import com.arcbbs.mapper.UserInfoMapper;
import com.arcbbs.mapper.UserIntegralRecordMapper;
import com.arcbbs.mapper.UserMessageMapper;
import com.arcbbs.service.EmailCodeService;
import com.arcbbs.service.UserInfoService;
import com.arcbbs.utils.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private EmailCodeService emailCodeService;
    @Resource
    private UserMessageMapper userMessageMapper;
    @Resource
    private UserIntegralRecordMapper userIntegralRecordMapper;
@Resource
private FileUtils fileUtils;
    public List<UserInfo> select() {
        return userInfoMapper.selectlist();
    }

    @Transactional(rollbackFor = Exception.class)
    public void register(String email, String emailCode, String nickName, String password) {

        UserInfo userInfo = userInfoMapper.selectbyemail(email);
        if (userInfo != null) {
            throw new BaseException("邮箱已存在");
        }
//        if(null == userInfo){
//            throw new BaseException("该账号已存在");
//        }
        emailCodeService.checkcode(email, emailCode);
        String userId = StringTools.getRandomNumber(BaseConstant.LENGTH_10);

        UserInfo insertinfo = new UserInfo();
        insertinfo.setUserId(userId);
        insertinfo.setNickName(nickName);
        insertinfo.setEmail(email);
        insertinfo.setPassword(StringTools.md5(password));
        insertinfo.setJoinTime(new Date());
        insertinfo.setStatus(1);
        insertinfo.setCurrentIntegral(BaseConstant.ZERO);
        insertinfo.setTotalIntegral(BaseConstant.ZERO);
        System.out.println(insertinfo);
        userInfoMapper.insert(insertinfo);

        updateUserIntegral(userId, UserIntegralOperTypeEnum.REGISTER, 1, 5);
        //记录消息
        UserMessage userMessage = new UserMessage();
        userMessage.setReceivedUserId(userId);
        userMessage.setMessageType(0);
        userMessage.setCreateTime(new Date());
        userMessage.setStatus(0);
        userMessage.setMessageContent(SysCacheUtils.getSysSetting().getSystemSettingRegisterDto().getRegisterWelcomInfo());
        userMessageMapper.insert(userMessage);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserIntegral(String userId, UserIntegralOperTypeEnum userIntegralOperTypeEnum, Integer changeType, Integer integral) {
        integral = changeType * integral;
        if (changeType == 0) {
            return;
        }
        UserInfo userInfo = userInfoMapper.selectbyuserid(userId);
        if (changeType.equals(-1) && userInfo.getCurrentIntegral() + integral < 0) {
            integral = changeType * userInfo.getCurrentIntegral();


        }

        UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
        userIntegralRecord.setUserId(userId);
        userIntegralRecord.setIntegral(integral);
        userIntegralRecord.setCreateTime(new Date());
        userIntegralRecord.setOperType(changeType);
        userIntegralRecordMapper.insert(userIntegralRecord);

        Integer count = userInfoMapper.updateIntegral(userId, integral);
        if (count == 0) {
            throw new BaseException("更新用户积分失败");

        }

    }

    @Resource
    private WebConfig webConfig;

    public SessionWebUserDto login(String email, String password, String ip) {
        UserInfo userInfo = userInfoMapper.selectbyemail(email);
        password = StringTools.md5(password);
        if (null == userInfo || !userInfo.getPassword().equals(password)) {
            throw new BaseException("账号或密码错误");
        }
        System.out.println(userInfo.getStatus() + "status");
        if (userInfo.getStatus().equals(0)) {
            throw new BaseException("账号已禁用");
        }
        Map<String, String> ipaddress = getip(ip);
        System.out.println(ipaddress);
        UserInfo updateinfo = new UserInfo();
        updateinfo.setLastLoginTime(new Date());
        updateinfo.setLastLoginIp(ipaddress.get("pro"));
        updateinfo.setLastLoginIp(ipaddress.get("ip"));
        userInfoMapper.update(userInfo);
        SessionWebUserDto sessionWebUserDt = new SessionWebUserDto();
        sessionWebUserDt.setNickName(userInfo.getNickName());
        sessionWebUserDt.setProvince(ipaddress.get("pro"));
        sessionWebUserDt.setUserId(userInfo.getUserId());
        if (StringTools.isEmpty(webConfig.getAdminEmails()) && ArrayUtils.contains(webConfig.getAdminEmails().split(","), userInfo.getEmail())) {
            sessionWebUserDt.setIsAdmin(true);
        } else {
            sessionWebUserDt.setIsAdmin(false);
        }


        return sessionWebUserDt;
    }

    public Map<String, String> getip(String ip) {

        Map<String, String> addressInfo = new HashMap<>();
        try {
            String url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip;
            String responseJson = OKHttpUtils.getRequest(url);
            if (null == responseJson) {
                return null;
            }
            addressInfo = JsonUtils.convertJSON2Obj(responseJson, Map.class);
            return addressInfo;
        } catch (Exception e) {
            System.out.println(e);
            throw new BaseException("异常");
        }
//        return addressInfo;

    }

    @Transactional(rollbackFor = Exception.class)
    public void resetpwd(String email, String password, String emailcode, String checkcode) {
        UserInfo userInfo = userInfoMapper.selectbyemail(email);
        if (null == userInfo) {
            throw new BaseException("用户不存在");
        }
        emailCodeService.checkcode(email, emailcode);
        UserInfo updateinfo = new UserInfo();
        updateinfo.setUserId(userInfo.getUserId());
        updateinfo.setEmail(email);
        updateinfo.setPassword(StringTools.md5(password));
        userInfoMapper.update(updateinfo);
    }
    @Override
    public   UserInfo selectbyuserid(String userId){
        return userInfoMapper.selectbyuserid(userId);
    }
    @Override
    public     void update(UserInfo userInfo, MultipartFile avatar){
        userInfoMapper.update(userInfo);
        if(avatar !=null){
            fileUtils.uploadDto(avatar,userInfo.getUserId(),FileUploadTypeEnum.AVATAR);


        }
    }
}
